//
//  ProgressImageView.swift
//  01- 搭建框架
//
//  Created by apple on 15/10/28.
//  Copyright © 2015年 任伟. All rights reserved.
//

import UIKit

/// MARK: - 带进度的图像视图
class ProgressImageView: UIImageView {
    
    //外部传递加载进度 0 - 1
    var progress: CGFloat = 0 {
        didSet {
            progressView.progress = progress
            }
        }
    
    /// MARK: - 构造函数
    init() {
        super.init(frame: CGRectZero)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// MARK: - 设置界面
    private func setupUI() {
    
        // 1. 添加控件
        addSubview(progressView)
        progressView.backgroundColor = UIColor.clearColor()
        // 2. 设置布局
        progressView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
    }
    
    /// MARK: - 懒加载控件
    private lazy var progressView: ProgressView = ProgressView()
    
}


/// MARK: - 进度视图
private class ProgressView: UIView {
    
    //外部传递加载进度 0 - 1
    var progress: CGFloat = 0.6 {
        didSet {
            setNeedsDisplay()
        }
    }

    override func drawRect(rect: CGRect) {
        
        let center = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5)
        let radius = min(rect.width, rect.height) * 0.5
        let start = CGFloat(-M_PI_2)
        let end = start + progress * 2 * CGFloat(M_PI)
        
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: start, endAngle: end, clockwise: true)
        
        path.addLineToPoint(center)
        path.closePath()
        
       // UIColor(white: 1, alpha: 0.6).setFill()
        UIColor.purpleColor().setFill()
        
        path.fill()
    }
    
}